<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/3/11
 * Time: 12:51
 */

namespace app\admin\logic;

use app\common\model\mysql\Admin;
use think\Exception;
use think\exception\PDOException;
use think\facade\Log;

class AdminLogic extends BaseLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new Admin();
    }

    /**
     * @param $group_id
     * @param $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function saveData($group_id, $data)
    {
        $data['salt']     = getRandKey();
        $data['password'] = md5(md5($data['password']).$data['salt']);
        $res              = $this->model->saveData($group_id, $data);
        if ($res === false) {
            throw new \think\Exception("添加失败");
        }

        return true;
    }

    /**
     * @param $id
     * @param $group_id
     * @param $data
     * @return bool
     * @throws \think\Exception
     */
    public function updateAdminAndGroupAccessById($id, $data, $group_id)
    {
        // 这里获取一下已经生成的salt,如果要修改密码的话
        $admin_one        = $this->findOne($id);
        $salt             = $admin_one['salt'];
        $data['password'] = md5(md5($data['password']).$salt);
        $res              = $this->model->updateAdminAndGroupAccessById($id, $data, $group_id);
        if ($res === false) {
            throw new \think\Exception("编辑失败");
        }

        return true;
    }

    /**
     * @param $id
     * @return bool
     * @throws \think\Exception
     */
    public function deleteById($id)
    {
        $res = $this->model->deleteById($id);
        if (false === $res) {
            throw new \think\Exception("角色删除失败");
        }

        return true;
    }

    public function login($username, $password)
    {
        $admin_one = $this->model->where('username', $username)->find();
        if (!empty($admin_one) && $admin_one['password'] == md5(md5($password).$admin_one['salt'])) {
            // 表示登录成功
            session('uid', $admin_one['id']);
            session('username', $admin_one['username']);
            session('nickname', $admin_one['nickname']);
            session('is_admin', $admin_one['is_admin']);

            $data = [
                'last_login_time' => time(),
                'last_login_ip'   => request()->ip(),
            ];

            try {
                $this->model->where('id', $admin_one['id'])->update($data);
            } catch (PDOException $e) {
                Log::record($e->getMessage());
            } catch (Exception $e) {
                Log::record($e->getMessage());
            }

            return true;
        } else {
            return false;
        }
    }
}